package com.mmall.controller.backend;

import com.google.common.collect.Maps;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.Product;
import com.mmall.service.IFileService;
import com.mmall.service.IProductService;
import com.mmall.service.IUserService;
import com.mmall.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;


/**
 * @Author: Czh
 * @Date: 2019/4/18  12:36
 * @Version: 1.0
 **/
@RestController
@RequestMapping("/manage/product/")
public class ProductManageController {


    @Autowired
    private IUserService iUserService;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private IFileService iFileService;


    @RequestMapping(value = "save.do" ,method = RequestMethod.POST)
    public ServerResponse saveAndUpdateProduct(HttpServletRequest httpServletRequest, Product product){
//        //User user = (User) session.getAttribute(Const.CURRENT_USER);
//        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
//        if(StringUtils.isEmpty(loginToken)){
//            return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");
//        }
//        String userJsonStr = RedisShardedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonStr,User.class);
//        if (user == null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode() , "用户未登录，请登录");
//        }
//        if (iUserService.checkAdminRole(user).isSuccess()){
//            //是管理员
//            // todo 添加处理逻辑
//            return iProductService.saveAndUpdateProduct(product);
//        } else {
//            return ServerResponse.createByErrorMessage("无权限，需要管理员权限");
//        }
        //全部通过拦截器验证是否登录以及权限
        return iProductService.saveAndUpdateProduct(product);

    }

    @RequestMapping(value = "set_sale_status.do",method = RequestMethod.POST)
    public ServerResponse setSaleStatus(HttpServletRequest httpServletRequest, Integer productId , Integer status){
//        //User user = (User) session.getAttribute(Const.CURRENT_USER);
//        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
//        if(StringUtils.isEmpty(loginToken)){
//            return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");
//        }
//        String userJsonStr = RedisShardedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonStr,User.class);
//        if (user == null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode() , "用户未登录，请登录");
//        }
//        if (iUserService.checkAdminRole(user).isSuccess()){
//            //是管理员
//            // todo 添加处理逻辑
//            return iProductService.setSaleStatus(productId , status);
//        } else {
//            return ServerResponse.createByErrorMessage("无权限，需要管理员权限");
//        }
        //全部通过拦截器验证是否登录以及权限
        return iProductService.setSaleStatus(productId , status);

    }
    @RequestMapping(value = "detail.do",method = RequestMethod.POST)
    public ServerResponse getDetail(HttpServletRequest httpServletRequest , Integer productId){
//        //User user = (User) session.getAttribute(Const.CURRENT_USER);
//        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
//        if(StringUtils.isEmpty(loginToken)){
//            return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");
//        }
//        String userJsonStr = RedisShardedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonStr,User.class);
//        if (user == null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode() , "用户未登录，请登录");
//        }
//        if (iUserService.checkAdminRole(user).isSuccess()){
//            //是管理员
//            // todo 添加处理逻辑
//            return iProductService.manageProductDetail(productId);
//        } else {
//            return ServerResponse.createByErrorMessage("无权限，需要管理员权限");
//        }
        //全部通过拦截器验证是否登录以及权限
        return iProductService.manageProductDetail(productId);

    }

    @RequestMapping(value = "list.do",method = RequestMethod.POST)
    public ServerResponse getList(HttpServletRequest httpServletRequest ,
                                  @RequestParam(value = "pageNum" , defaultValue = "1") int pageNum ,
                                  @RequestParam(value = "pageSize" , defaultValue = "10") int pageSize){
//        //User user = (User) session.getAttribute(Const.CURRENT_USER);
//        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
//        if(StringUtils.isEmpty(loginToken)){
//            return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");
//        }
//        String userJsonStr = RedisShardedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonStr,User.class);
//        if (user == null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode() , "用户未登录，请登录");
//        }
//        if (iUserService.checkAdminRole(user).isSuccess()){
//            //是管理员
//            // todo 添加处理逻辑
//            return iProductService.getProductList(pageNum,pageSize);
//        }else {
//            return ServerResponse.createByErrorMessage("无权限，需要管理员权限");
//        }
        //全部通过拦截器验证是否登录以及权限
        return iProductService.getProductList(pageNum,pageSize);

    }

    @RequestMapping(value = "search.do",method = RequestMethod.POST)
    public ServerResponse productSearch(HttpServletRequest httpServletRequest , String productName , Integer productId ,
                                        @RequestParam(value = "pageNum" , defaultValue = "1") int pageNum ,
                                        @RequestParam(value = "pageSize" , defaultValue = "10") int pageSize){
//        //User user = (User) session.getAttribute(Const.CURRENT_USER);
//        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
//        if(StringUtils.isEmpty(loginToken)){
//            return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");
//        }
//        String userJsonStr = RedisShardedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonStr,User.class);
//        if (user == null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode() , "用户未登录，请登录");
//        }
//        if (iUserService.checkAdminRole(user).isSuccess()){
//            //是管理员
//            // todo 添加处理逻辑
//            return iProductService.searchProduct(productName , productId , pageNum , pageSize);
//        }else {
//            return ServerResponse.createByErrorMessage("无权限，需要管理员权限");
//        }
        //全部通过拦截器验证是否登录以及权限
        return iProductService.searchProduct(productName , productId , pageNum , pageSize);

    }

    @RequestMapping(value = "upload.do",method = RequestMethod.POST)
    public ServerResponse upload( @RequestParam(value = "file" , required = false) MultipartFile file1,
                                 HttpServletRequest request , HttpServletRequest httpServletRequest ){
//        //User user = (User)session.getAttribute(Const.CURRENT_USER);
//        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
//        if(StringUtils.isEmpty(loginToken)){
//            return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");
//        }
//        String userJsonStr = RedisShardedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonStr,User.class);
//        if(user == null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),
//                    "用户未登录,请登录管理员");
//        }
//        if(iUserService.checkAdminRole(user).isSuccess()){
//            String path = request.getSession().getServletContext().getRealPath("upload");
//            String targetFileName = iFileService.upload(file1 , path);
//            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
//
//            Map fileMap = Maps.newHashMap();
//            fileMap.put("uri",targetFileName);
//            fileMap.put("url",url);
//            return ServerResponse.createBySuccess(fileMap);
//        }else{
//            return ServerResponse.createByErrorMessage("无权限操作");
//        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file1 , path);
        String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
        Map fileMap = Maps.newHashMap();
        fileMap.put("uri",targetFileName);
        fileMap.put("url",url);
        return ServerResponse.createBySuccess(fileMap);
    }

    @RequestMapping(value = "richtext_img_upload.do",method = RequestMethod.POST)
    public Map richtextImgUpload(@RequestParam(value="file" , required = false)MultipartFile file, HttpServletRequest httpServletRequest, HttpServletResponse response , HttpSession session) {
        Map resultMap = Maps.newHashMap();
//        //User user = (User)session.getAttribute(Const.CURRENT_USER);
//        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
//        if(StringUtils.isEmpty(loginToken)){
//            resultMap.put("success",false);
//            resultMap.put("msg","用户未登录");
//            return resultMap;
//        }
//        String userJsonStr = RedisShardedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonStr,User.class);
//
//        if(user == null){
//            resultMap.put("success",false);
//            resultMap.put("msg","请登录管理员");
//            return resultMap;
//        }
//        //富文本中对于返回值有自己的要求,我们使用是simditor所以按照simditor的要求进行返回
////        {
////            "success": true/false,
////                "msg": "error message", # optional
////            "file_path": "[real file path]"
////        }
//        if(iUserService.checkAdminRole(user).isSuccess()){
//            String path = httpServletRequest.getSession().getServletContext().getRealPath("upload");
//            String targetFileName = iFileService.upload(file,path);
//            if(StringUtils.isBlank(targetFileName)){
//                resultMap.put("success",false);
//                resultMap.put("msg","上传失败");
//                return resultMap;
//            }
//            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
//            resultMap.put("success",true);
//            resultMap.put("msg","上传成功");
//            resultMap.put("file_path",url);
//            response.addHeader("Access-Control-Allow-Headers","X-File-Name");
//            return resultMap;
//        }else{
//            resultMap.put("success",false);
//            resultMap.put("msg","无权限操作");
//            return resultMap;
//        }
        String path = httpServletRequest.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file, path);
        if (StringUtils.isBlank(targetFileName)) {
            resultMap.put("success", false);
            resultMap.put("msg", "上传失败");
            return resultMap;
        }
        String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
        resultMap.put("success", true);
        resultMap.put("msg", "上传成功");
        resultMap.put("file_path", url);
        response.addHeader("Access-Control-Allow-Headers", "X-File-Name");
        return resultMap;

    }

}
